package com.tbit.uqbike.client.controller;

import com.tbit.uqbike.client.constant.ResponseCode;
import com.tbit.uqbike.client.exception.BaseException;
import com.tbit.uqbike.client.pojo.Point;
import com.tbit.uqbike.client.service.CalibrateService;
import com.tbit.uqbike.client.util.Assert;
import com.tbit.uqbike.client.util.OutputUtil;
import com.tbit.uqbike.client.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 通用校准接口
 *
 * @author Leon
 * 2017年2月24日 下午5:51:05
 */
@Controller
@RequestMapping("/calibrate")
public class CalibrateController {
    @Autowired
    private CalibrateService calibrateService;


    /**
     * 通用校准接口
     *
     * @param from     源地图类型
     * @param to       需要转化的地图类型
     * @param x        经度
     * @param y        纬度
     * @param session  会话
     * @param response 响应
     * @ignoreParams request
     */
    @RequestMapping("/commonOriginal")
    public void commonOriginal(Integer from, Integer to, String x, String y, HttpSession session,
                               HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            /* 校验 */
            Assert.notNull(from, "-2007", "转换前经纬度类型不能为空");
            Assert.notNull(to, "-2008", "转换后经纬度类型不能为空");
            Assert.hasLength(x, "-2001", "经度不能为空");
            Assert.hasLength(y, "-2002", "纬度不能为空");

            List<Double> lons = StringUtil.getDoubleList(x);
            List<Double> lats = StringUtil.getDoubleList(y);

            List<Point> points = new ArrayList<Point>();
            for (int i = 0, length = lons.size(); i < length; i++) {
                points.add(new Point(lons.get(i), lats.get(i)));
            }

            List<Point> clibratePoints = new ArrayList<Point>();
            for (Point p : points) {
                clibratePoints.add(calibrateService.calibrate(p, from, to));
            }


            map.put(ResponseCode.RET, ResponseCode.SUCC);
            map.put(ResponseCode.DATA, clibratePoints);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }

        OutputUtil.renderText(request, response, map);
    }


}